import { useState, useEffect, useMemo, useRef } from 'react';
import { 
  Layout, 
  Menu, 
  Dropdown, 
  Avatar, 
  message, 
  Button, 
  Input, 
  Tabs, 
  Badge, 
  List 
} from '@/utils/antd-imports';
import { 
  UserOutlined,
  DashboardOutlined,
  ProjectOutlined,
  TeamOutlined,
  MoneyCollectOutlined,
  ApartmentOutlined,
  SettingOutlined,
  LogoutOutlined,
  FileOutlined,
  FileTextOutlined,
  ClockCircleOutlined,
  FileAddOutlined,
  FileDoneOutlined,
  SwapOutlined,
  DollarOutlined,
  FileSyncOutlined,
  FileProtectOutlined,
  AuditOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  SearchOutlined,
  BookOutlined,
  CloseOutlined,
  BellFilled,
  PieChartOutlined,
  SolutionOutlined,
  CheckCircleOutlined,
  CarOutlined,
  SafetyCertificateOutlined 
} from '@/utils/icons';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import ContractManagement from './Contract-Management/ContractManagement';
import ProjectEditForm from './project-manager/Project-Initiation/ProjectEditForm';
import PersonalSettings from '../components/PersonalSettings';
import TutorialGuide from '../components/TutorialGuide';
import MemberProjectList from './project-manager/Project-Members/MemberProjectList';
import ProjectMembers from './project-manager/Project-Members/ProjectMembers';
import ProjectList from './project-manager/Project-Initiation/ProjectList';
import ProjectForm from './project-manager/Project-Initiation/ProjectForm';
import ArchiveManagement from './employee-manager/ArchiveManagement';
import EmployeeContracts from './employee-manager/EmployeeContracts';
import ApprovalSettings from './Review-Center/ApprovalSettings';
import SubProjectTable from './project-manager/Project-Initiation/SubProjectTable';
import Workbench from '../components/Workbench';
import NotificationCenter from '../components/NotificationCenter';
import ResignationApproval from './Review-Center/ResignationApproval';
import ProjectApproval from './Review-Center/ProjectApproval';
import InvoiceApproval from './Review-Center/InvoiceApproval';
import EmployeeRoster from './employee-manager/EmployeeRoster';
import EmployeeForm from './employee-manager/EmployeeForm';
import ProjectSettlementList from './project-manager/Project-Settlement/ProjectSettlementList';
import CompanyEntity from './project-manager/CompanyEntity';
import CustomerInfo from './project-manager/CustomerInfo';
import ProjectSettlementForm from './project-manager/Project-Settlement/ProjectSettlementForm';
import OutputStatistics from './output-value-center/OutputStatistics';
import OutputReports from './output-value-center/OutputReports';
import FinanceOverview from './finance-management/FinanceOverview';
import SalaryManagement from './salary-management/SalaryManagement';
import ExpenseManagement from './expense-management/ExpenseManagement';
import AssetManagement from './asset-management/AssetManagement';
import VehicleManagement from './vehicle-management/VehicleManagement';
import SupplierManagement from './supplier-management/SupplierManagement';
import UserManagement from './organization/UserManagement';
import OrganizationStructure from './organization/OrganizationStructure';
import logo from '../assets/logo.png';

const { Sider, Content, Header } = Layout;
const { Search } = Input;
const { TabPane } = Tabs;

// 获取菜单项的完整路径
const getMenuPath = (key, items) => {
  for (const item of items) {
    if (item.key === key) {
      return [{ key: item.key, label: item.label }];
    }
    if (item.children) {
      const childPath = getMenuPath(key, item.children);
      if (childPath.length > 0) {
        return [{ key: item.key, label: item.label }, ...childPath];
      }
    }
  }
  return [];
};

// 扁平化菜单项用于搜索
const flattenMenuItems = (items) => {
  let result = [];
  items.forEach(item => {
    if (item.children) {
      result = [...result, ...flattenMenuItems(item.children)];
    } else {
      result.push({
        key: item.key,
        label: item.label,
        icon: item.icon
      });
    }
  });
  return result;
};

export default function Dashboard() {
  const navigate = useNavigate();
  const { user, logout } = useAuth();
  const [selectedKey, setSelectedKey] = useState('dashboard');
  const [openKeys, setOpenKeys] = useState(['project']);
  const [collapsed, setCollapsed] = useState(false);
  const [activeTab, setActiveTab] = useState('dashboard');
  const [tabs, setTabs] = useState([
    { key: 'dashboard', label: '工作台', closable: false }
  ]);
  const [searchResults, setSearchResults] = useState([]);
  const [searchVisible, setSearchVisible] = useState(false);
  const employeeRosterRef = useRef(null);
  const projectListRef = useRef(null);

  // 特殊视图的组件映射
  const specialViews = {
    'project-form': (data) => <ProjectForm mode={data?.mode || 'create'} projectId={data?.projectId} projectCode={data?.projectCode} onBack={handleProjectSelect} />,
    'project-edit': (data) => <ProjectEditForm 
      mode="edit"
      projectId={data.projectId} 
      projectCode={data.projectCode}
      subProjectName={data.subProjectName}
      onBack={handleProjectSelect} 
    />,
    'project-detail': (data) => <SubProjectTable projectId={data?.projectId} projectCode={data?.projectCode} projectName={data?.projectName} onProjectSelect={handleProjectSelect}  />,    'member-detail': (data) => <ProjectMembers projectId={data?.projectId} projectCode={data?.projectCode} />,    'settlement-detail': (data) => <ProjectSettlementForm projectId={data?.projectId} projectCode={data?.projectCode} />,    'employee-form': (data) => <EmployeeForm mode={data?.mode || 'create'} employeeId={data?.employeeId} onBack={handleEmployeeFormComplete} />,
    'employee-edit': (data) => <EmployeeForm mode="edit" employeeId={data?.employeeId} onBack={handleEmployeeFormComplete} />,
    'settings': () => <PersonalSettings />,
    'guide': () => <TutorialGuide />,
    'output-statistics': () => <OutputStatistics />,
    // 'output-distribution': () => <OutputDistribution />, // 暂时注释掉，组件未定义
    'output-reports': () => <OutputReports />,
  };

  // 当前视图状态
  const [currentView, setCurrentView] = useState({
    type: 'menu', // 'menu' | 'special'
    key: 'dashboard',
    data: null
  });

  // 处理员工表单完成
  const handleEmployeeFormComplete = (result) => {
    if (result && result.close) {
      // 判断是创建还是编辑模式
      const isEditMode = currentView.key === 'employee-edit' || activeTab.includes('edit');
      
      // 关闭当前员工表单页签
      handleTabClose(activeTab);
      
      // 添加或切换到员工花名册页签
      const rosterTabExists = tabs.find(tab => tab.key === 'employee-roster');
      if (!rosterTabExists) {
        // 如果员工花名册页签不存在，添加它
        setTabs(prevTabs => [...prevTabs, {
          key: 'employee-roster',
          label: '员工花名册',
          closable: true
        }]);
      }
      
      // 刷新员工花名册数据
      if (employeeRosterRef.current) {
        employeeRosterRef.current.refreshData();
      }
      
      // 切换到员工花名册页签
      setTimeout(() => {
        setActiveTab('employee-roster');
        setCurrentView({
          type: 'menu',
          key: 'employee-roster',
          data: null
        });
        setSelectedKey('employee-roster');
        setOpenKeys(['personnel']);
      }, 100);
      
      message.success(isEditMode 
        ? `员工 ${result.employeeName} 更新成功` 
        : `员工 ${result.employeeName} 创建成功`);
    }
  };

  function handleProjectSelect(data) {
    let newTabKey = '';
    let newTabLabel = '';
    let viewType = '';
    let menuKey = '';
    let shouldAddRosterTab = false;
    
    switch(data.type) {
      case 'menu-navigation':
        // 处理从工作台常用功能的菜单导航
        newTabKey = data.key;
        newTabLabel = data.label;
        viewType = '';
        menuKey = data.key;
        break;
      case 'create-employee':
        newTabKey = 'employee-form-create';
        newTabLabel = '新增员工';
        viewType = 'employee-form';
        menuKey = 'employee-roster';
        // 标记需要添加员工花名册页签
        shouldAddRosterTab = true;
        break;
      case 'edit-employee':
        newTabKey = `employee-form-edit-${data.employeeId}`;
        newTabLabel = `编辑-${data.label?.replace('编辑-', '') || '员工'}`;
        viewType = 'employee-edit';
        menuKey = 'employee-roster';
        // 标记需要添加员工花名册页签
        shouldAddRosterTab = true;
        break;
      case 'create-member':
        newTabKey = 'employee-form-create';
        newTabLabel = '新增员工';
        viewType = 'employee-form';
        menuKey = 'employee-roster';
      break;
      case 'project-detail':
        newTabKey = `project-detail-${data.projectId}`;
        newTabLabel = `详情-${data.projectName}`;        viewType = 'project-detail';
        menuKey = 'project-list';
        break;
      case 'project-edit':  // 新增编辑项目的case
        newTabKey = `project-edit-${data.projectId}`;
        newTabLabel = `编辑-${data.subProjectName || data.projectCode}`;
        viewType = 'project-edit';
        menuKey = 'project-list';
      break;
      case 'create':
        newTabKey = 'project-form-create';
        newTabLabel = '新建项目';
        viewType = 'project-form';
        menuKey = 'project-list';
        data.projectCode = data.projectCode || ''; 
        break;
      case 'edit':
        newTabKey = `project-form-edit-${data.projectId}`;
        newTabLabel = `编辑-${data.projectName}`;        viewType = 'project-form';
        menuKey = 'project-list';
        break;
      case 'member-detail':
        newTabKey = `member-detail-${data.projectId}`;
        newTabLabel = `成员-${data.projectName}`;        viewType = 'member-detail';
        menuKey = 'project-members';
        break;
      case 'settlement-detail':
        newTabKey = `settlement-detail-${data.projectId}`;
        newTabLabel = `结算-${data.projectName}`;        viewType = 'settlement-detail';
        menuKey = 'project-settlement';
        break;
      case 'project-form-complete':
        // 先关闭新建项目表单页签
        const formTabKey = tabs.find(tab => tab.viewType === 'project-form')?.key;
        if (formTabKey) {
          handleTabClose(formTabKey);
        }
        
        // 如果设置了关闭标志，返回到项目立项页面
        if (data.close) {
          // 刷新项目立项页面数据
          if (data.refresh && projectListRef.current) {
            projectListRef.current.refreshData();
            console.log('项目立项成功，已刷新项目列表');
          }
          
          // 确保切换到项目立项列表页面
          setCurrentView({
            type: 'menu',
            key: 'project-list',
            data: null
          });
          
          // 设置活动标签页为项目立项
          setActiveTab('project-list');
          return;
        }
        
        // 否则打开项目详情页
        newTabKey = `project-detail-${data.projectId}`;
        newTabLabel = `详情-${data.projectName}`;
        viewType = 'project-detail';
        menuKey = 'project-list';
        break;
      default:
        return;
    }

    if (data.type === 'menu-navigation') {
      // 菜单导航添加新标签页
      const tabExists = tabs.some(tab => tab.key === data.key);
      
      if (!tabExists) {
        addTab({
          key: data.key,
          label: data.label,
          closable: data.key !== 'dashboard'
        });
      }
      
      setCurrentView({
        type: 'menu',
        key: data.key,
        data: null
      });
      setSelectedKey(data.key);
      if (data.parentKey) {
        setOpenKeys([data.parentKey]);
      }
    } else {
      // 如果需要添加员工花名册页签
      if (shouldAddRosterTab && !tabs.find(tab => tab.key === 'employee-roster')) {
        setTabs([...tabs, {
          key: 'employee-roster',
          label: '员工花名册',
          closable: true
        }]);
      }
      
      addTab({
        key: newTabKey,
        label: newTabLabel,
        closable: true,
        viewType,
        viewData: data
      });

      setCurrentView({
        type: 'special',
        key: viewType,
        data
      });

      setSelectedKey(menuKey);
      
      // 根据不同的视图类型设置不同的展开菜单
      if (viewType === 'employee-form') {
        setOpenKeys(['personnel']);
      } else {
        setOpenKeys(['project']);
      }
    }
  }

  // 菜单配置
  const menuItems = useMemo(() => [
    {
      key: 'dashboard',
      icon: <DashboardOutlined />,
      label: '工作台',
      component: <Workbench onProjectSelect={handleProjectSelect} getMenuItems={() => menuItems} />
    },
    {
      key: 'personnel',
      icon: <TeamOutlined />,
      label: '人事管理',
      children: [
        {
          key: 'employee-roster',
          icon: <SolutionOutlined />,
          label: '员工花名册',
          component: <EmployeeRoster ref={employeeRosterRef} onMemberSelect={handleProjectSelect} />
        },
        {
          key: 'employee-files',
          icon: <FileOutlined />,
          label: '档案管理',
          component: <ArchiveManagement />
        },
        {
          key: 'employee-contracts',
          icon: <FileTextOutlined />,
          label: '员工合同',
          component: <EmployeeContracts />
        }
      ]
    },
    {
      key: 'project',
      icon: <ProjectOutlined />,
      label: '项目管理',
      children: [
        {
          key: 'project-list',
          icon: <FileAddOutlined />,
          label: '项目立项',
          component: <ProjectList ref={projectListRef} onProjectSelect={handleProjectSelect} />
        },
        {
          key: 'project-members',
          icon: <TeamOutlined />,
          label: '项目成员',
          component: <MemberProjectList onProjectSelect={handleProjectSelect} />
        },
        {
          key: 'project-settlement',
          icon: <DollarOutlined />,
          label: '项目结算',
          component: <ProjectSettlementList onProjectSelect={handleProjectSelect} />
        },
        {
          key: 'company-entity',
          icon: <ApartmentOutlined />,
          label: '公司主体',
          component: <CompanyEntity />
        },
        {
          key: 'customer-info',
          icon: <TeamOutlined />,
          label: '客户信息',
          component: <CustomerInfo />
        }
      ]
    },
    {
      key: 'approval',
      icon: <AuditOutlined />,
      label: '审批中心',
      children: [
        {
          key: 'project-approval',
          icon: <ProjectOutlined />,
          label: '项目审批',
          component: <ProjectApproval />
        },
        {
          key: 'invoice-approval',
          icon: <FileTextOutlined />,
          label: '开票审批',
          component: <InvoiceApproval />
        },
        {
          key: 'resignation-approval',
          icon: <SwapOutlined />,
          label: '离职审批',
          component: <ResignationApproval />
        },
        {
          key: 'approval-settings',
          icon: <CheckCircleOutlined />,
          label: '审批设置',
          component: <ApprovalSettings />
        }
      ]
    },
    {
      key: 'output-value',
      icon: <PieChartOutlined />,
      label: '产值中心',
      children: [
        {
          key: 'output-statistics',
          icon: <PieChartOutlined />,
          label: '产值统计',
          component: <OutputStatistics />
        },
        {
          key: 'output-reports',
          icon: <FileTextOutlined />,
          label: '产值报表',
          component: <OutputReports />
        }
      ]
    },
    {
      key: 'contract',
      icon: <FileProtectOutlined />,
      label: '合同管理',
      component: <ContractManagement />
    },
    {
      key: 'finance-management',
      icon: <MoneyCollectOutlined />,
      label: '财务管理',
      children: [
        {
          key: 'finance-overview',
          icon: <PieChartOutlined />,
          label: '财务概览',
          component: <FinanceOverview />
        }
      ]
    },
    {
      key: 'salary-management',
      icon: <DollarOutlined />,
      label: '薪资管理',
      component: <SalaryManagement />
    },
    {
      key: 'expense-management',
      icon: <FileTextOutlined />,
      label: '报销申请',
      component: <ExpenseManagement />
    },
    {
      key: 'asset-management',
      icon: <SafetyCertificateOutlined />,
      label: '资产管理',
      children: [
        {
          key: 'fixed-assets',
          icon: <SafetyCertificateOutlined />,
          label: '固定资产',
          component: <AssetManagement />
        },
        {
          key: 'current-assets',
          icon: <SwapOutlined />,
          label: '流动资产',
          component: <AssetManagement />
        }
      ]
    },
    {
      key: 'vehicle-management',
      icon: <CarOutlined />,
      label: '车辆管理',
      component: <VehicleManagement />
    },
    {
      key: 'supplier-management',
      icon: <TeamOutlined />,
      label: '供应商管理',
      component: <SupplierManagement />
    },
    {
      key: 'organization',
      icon: <ApartmentOutlined />,
      label: '组织架构',
      component: <OrganizationStructure />
    },
    {
      key: 'user-management',
      icon: <UserOutlined />,
      label: '用户管理',
      component: <UserManagement />
    }
  ], []);

  // 添加页签
  const addTab = (newTab) => {
    const existingTabIndex = tabs.findIndex(tab => tab.key === newTab.key);
    
    if (existingTabIndex !== -1) {
      const updatedTabs = [...tabs];
      updatedTabs[existingTabIndex] = {
        ...updatedTabs[existingTabIndex],
        ...newTab
      };
      setTabs(updatedTabs);
    } else {
      setTabs([...tabs, newTab]);
    }
    
    // 立即更新activeTab
    setActiveTab(newTab.key);
    
    // 立即更新currentView
    if (newTab.viewType) {
      // 特殊视图
      setCurrentView({
        type: 'special',
        key: newTab.viewType,
        data: newTab.viewData
      });
    } else {
      // 菜单视图
      setCurrentView({
        type: 'menu',
        key: newTab.key,
        data: null
      });
    }
  };

  // 处理页签切换
  const handleTabChange = (key) => {
    const tab = tabs.find(t => t.key === key);
    
    if (!tab) return;
    
    setActiveTab(key);
    
    if (tab.viewType) {
      // 特殊视图
      setCurrentView({
        type: 'special',
        key: tab.viewType,
        data: tab.viewData
      });

      // 根据视图类型设置对应的菜单选中状态
      let menuKey = '';
      switch(tab.viewType) {
        case 'project-detail':
          menuKey = 'project-list';
          break;
        case 'member-detail':
          menuKey = 'project-members';
          break;
        case 'settlement-detail':
          menuKey = 'project-settlement';
          break;
        case 'employee-form':
        case 'employee-edit':
          menuKey = 'employee-roster';
          break;
        default:
          menuKey = selectedKey;
      }
      setSelectedKey(menuKey);
      // 根据不同的视图类型设置不同的展开菜单
      if (tab.viewType === 'employee-form' || tab.viewType === 'employee-edit') {
        setOpenKeys(['personnel']);
      } else {
        setOpenKeys(['project']);
      }
    } else {
      // 菜单视图
      setCurrentView({
        type: 'menu',
        key: tab.key,
        data: null
      });
      setSelectedKey(tab.key);
    }
  };

  // 关闭页签
  const handleTabClose = (targetKey) => {
    const tabIndex = tabs.findIndex(tab => tab.key === targetKey);
    const newTabs = tabs.filter(tab => tab.key !== targetKey);
    
    if (newTabs.length === 0) {
      return;
    }
    
    let newActiveTab = activeTab;
    
    if (targetKey === activeTab) {
      // 如果关闭的是当前激活的tab，则激活前一个或后一个tab
      newActiveTab = tabs[tabIndex - 1]?.key || tabs[tabIndex + 1]?.key || 'dashboard';
    }
    
    setTabs(newTabs);
    setActiveTab(newActiveTab);
    handleTabChange(newActiveTab);
  };

  // 获取当前显示的组件
  const getCurrentComponent = () => {
    if (currentView.type === 'special') {
      const viewRenderer = specialViews[currentView.key];
      return viewRenderer ? viewRenderer(currentView.data) : null;
    }
    
    // 查找一级菜单
    const mainItem = menuItems.find(item => item.key === currentView.key);
    if (mainItem && mainItem.component) {
      return mainItem.component;
    }
    
    // 查找子菜单
    for (const item of menuItems) {
      if (item.children) {
        const childItem = item.children.find(child => child.key === currentView.key);
        if (childItem) {
          return childItem.component;
        }
      }
    }
    
    return <Workbench />;
  };

  const handleLogout = async () => {
    try {
      await logout();
      message.success('已退出登录');
      navigate('/login');
    } catch (error) {
      console.error('退出登录失败:', error);
      message.error('退出登录失败，请重试');
    }
  };

  const handleSettings = () => {
    addTab({
      key: 'settings',
      label: '个人设置',
      closable: true,
      viewType: 'settings'
    });
    // 确保视图更新
    setCurrentView({
      type: 'special',
      key: 'settings',
      data: null
    });
  };

  const handleGuide = () => {
    addTab({
      key: 'guide',
      label: '教程指南',
      closable: true,
      viewType: 'guide'
    });
    // 确保视图更新
    setCurrentView({
      type: 'special',
      key: 'guide',
      data: null
    });
  };

  const toggleCollapsed = () => {
    setCollapsed(!collapsed);
  };

  // 处理搜索
  const handleSearch = (value) => {
    if (!value) {
      setSearchResults([]);
      setSearchVisible(false);
      return;
    }
    
    const flattenedMenu = flattenMenuItems(menuItems);
    const results = flattenedMenu.filter(item => 
      item.label.toLowerCase().includes(value.toLowerCase())
    );
    
    setSearchResults(results);
    setSearchVisible(results.length > 0);
  };

  // 处理搜索结果点击
  const handleSearchResultClick = (key) => {
    setSearchVisible(false);
    
    let label = '';
    let parentKey = '';
    
    const findLabel = (items, parent = '') => {
      for (const item of items) {
        if (item.key === key) {
          return { label: item.label, parentKey: parent };
        }
        if (item.children) {
          const found = findLabel(item.children, item.key);
          if (found.label) return found;
        }
      }
      return { label: '', parentKey: '' };
    };
    
    const result = findLabel(menuItems);
    label = result.label;
    parentKey = result.parentKey;
    
    if (label) {
      addTab({
        key,
        label,
        closable: key !== 'dashboard'
      });
      
      // 设置正确的菜单选中状态
      if (parentKey) {
        setSelectedKey(key);
        setOpenKeys([parentKey]);
      } else {
        setSelectedKey(key);
      }
    }
    
    setCurrentView({
      type: 'menu',
      key,
      data: null
    });
  };


  const userMenu = (
    <Menu>
      <Menu.Item key="guide" icon={<BookOutlined />} onClick={handleGuide}>
        教程指南
      </Menu.Item>
      <Menu.Item key="settings" icon={<SettingOutlined />} onClick={handleSettings}>
        个人设置
      </Menu.Item>
      <Menu.Item key="logout" icon={<LogoutOutlined />} onClick={handleLogout}>
        退出登录
      </Menu.Item>
    </Menu>
  );


  // 处理菜单项点击
  const handleMenuClick = ({ key }) => {
    setSelectedKey(key);
    
    const tabExists = tabs.some(tab => tab.key === key);
    
    if (!tabExists) {
      const label = menuItems.find(item => item.key === key)?.label || 
        menuItems.flatMap(item => item.children || []).find(child => child.key === key)?.label;
      
      if (label) {
        addTab({
          key,
          label,
          closable: key !== 'dashboard'
        });
      }
    }
    
    setCurrentView({
      type: 'menu',
      key,
      data: null
    });
    setActiveTab(key);
  };

  return (
    <Layout style={{ minHeight: '100vh', overflow: 'hidden' }}>
      <Sider 
        width={200} 
        collapsedWidth={80}
        theme="dark" 
        collapsible
        collapsed={collapsed}
        onCollapse={toggleCollapsed}
        style={{ 
          boxShadow: '2px 0 8px 0 rgba(29, 35, 41, 0.1)',
          background: '#001529',
          height: '100vh',
          position: 'fixed',
          left: 0,
          zIndex: 100,
        }}
      >
        <div style={{ 
          padding: '16px', 
          textAlign: 'center', 
          borderBottom: '1px solid rgba(255, 255, 255, 0.1)',
          background: '#fff',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }}>
          {!collapsed ? (
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <img src={logo} alt="logo" style={{ height: '32px', marginRight: '8px' }} />
              <h2 style={{ 
                margin: 0,
                color: 'rgba(0, 0, 0, 0.85)',
                fontSize: '16px',
                fontWeight: '600'
              }}>凯泽利管理系统</h2>
            </div>
          ) : (
            <img src={logo} alt="logo" style={{ height: '32px' }} />
          )}
        </div>
        <div style={{ 
          height: 'calc(100vh - 120px)', 
          overflowY: 'auto',
          overflowX: 'hidden',
          scrollbarWidth: 'none',
          msOverflowStyle: 'none'
        }} className="sidebar-scroll-container">
          <Menu
            theme="dark"
            mode="inline"
            selectedKeys={selectedKey ? [selectedKey] : []}
            openKeys={openKeys}
            onOpenChange={(keys) => setOpenKeys(keys)}
            onClick={handleMenuClick}
            items={menuItems.map(item => ({
              key: item.key,
              icon: item.icon,
              label: item.label,
              children: item.children?.map(child => ({
                key: child.key,
                icon: child.icon,
                label: child.label
              }))
            }))}
            style={{ 
              background: '#001529',
              borderRight: 0,
              padding: '8px 0'
            }}
            inlineCollapsed={collapsed}
          />
        </div>
      </Sider>
      <Layout style={{ 
        marginLeft: collapsed ? 80 : 200,
        height: '100vh',
        overflow: 'hidden',
        transition: 'margin-left 0.2s'
      }}>
        <Header style={{ 
          background: '#fff',
          padding: '0 24px',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          boxShadow: '0 1px 4px rgba(0, 21, 41, 0.08)',
          position: 'sticky',
          top: 0,
          zIndex: 99
        }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Button
              type="text"
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={toggleCollapsed}
              style={{
                fontSize: '16px',
                width: 48,
                height: 48,
              }}
            />
          </div>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Dropdown
              overlay={
                <Menu style={{ maxHeight: 300, overflowY: 'auto' }}>
                  {searchResults.map(item => (
                    <Menu.Item 
                      key={item.key}
                      icon={item.icon}
                      onClick={() => handleSearchResultClick(item.key)}
                    >
                      {item.label}
                    </Menu.Item>
                  ))}
                </Menu>
              }
              visible={searchVisible && searchResults.length > 0}
              onVisibleChange={visible => setSearchVisible(visible)}
              placement="bottomRight"
            >
              <Search
                placeholder="搜索菜单..."
                allowClear
                style={{ width: 200, marginRight: 16 }}
                onChange={(e) => handleSearch(e.target.value)}
                onFocus={() => searchResults.length > 0 && setSearchVisible(true)}
              />
            </Dropdown>
            <div style={{ marginRight: '24px' }}>
              <NotificationCenter />
            </div>
            <Dropdown overlay={userMenu} placement="bottomRight">
              <div style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
                <Avatar 
                  style={{ 
                    marginRight: 8,
                    backgroundColor: '#1890ff',
                    fontSize: '16px',
                    fontWeight: 'bold'
                  }}
                >
                  {user?.username ? user.username.charAt(0) : 'U'}
                </Avatar>
                {!collapsed && <span>{user?.username || '用户'}</span>}
              </div>
            </Dropdown>
          </div>
        </Header>
        <div style={{ 
          background: '#fff',
          padding: '0 24px',
          borderBottom: '1px solid #f0f0f0'
        }}>
          <Tabs
            type="editable-card"
            hideAdd
            activeKey={activeTab}
            onChange={handleTabChange}
            onEdit={handleTabClose}
            style={{ marginBottom: -1 }}
          >
            {tabs.map(tab => (
              <TabPane
                key={tab.key}
                tab={tab.label}
                closable={tab.closable}
                closeIcon={<CloseOutlined style={{ fontSize: 12 }} />}
              />
            ))}
          </Tabs>
        </div>
        <Content style={{ 
          padding: '24px', 
          background: '#f5f7fa',
          height: 'calc(100vh - 112px)',
          overflowY: 'auto'
        }}>
          <div style={{ 
            background: '#fff', 
            minHeight: 'calc(100% - 48px)', 
            borderRadius: '4px',
            boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.03)'
          }}>
            {getCurrentComponent()}
          </div>
        </Content>
      </Layout>
    </Layout>
  );
}